﻿using ELab.Serialization.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ELab.Core.Serialization.Data
{
    public class QAProvider
    {
        private string _fileName = ELab.Settings.ELabSettings.AssemblyDirectory + "\\qa.lab";
        private List<Question> questions = null;
        public List<Question> Questions
        {
            get
            {
                if (questions != null) return questions;
                XmlSerializer x = new XmlSerializer(typeof(List<Question>));
                using (Stream stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
                {
                    if (stream.Length > 0)
                    {
                        var obj = x.Deserialize(stream);
                        if (obj != null)
                        {
                            questions = (List<Question>)obj;
                        }
                    }
                }
                if (questions == null) return new List<Question>();
                return questions;
            }
        }

        public void Add(params Question[] dest)
        {
            questions = this.Questions.AddExt(dest);
        }

        public void Save()
        {
            if (this.Questions == null) return;
            if (File.Exists(_fileName)) File.Delete(_fileName);

            XmlSerializer x = new XmlSerializer(typeof(List<Question>));
            using (Stream stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                x.Serialize(stream, this.Questions);
            questions = null;
        }

        public bool Exist(Question question)
        {
            return this.Questions.Any(x => x.QuestionValue == question.QuestionValue);
        }

        public void Remove(Question question)
        {
            var userCheck = this.Questions.FirstOrDefault(x => x.QuestionValue == question.QuestionValue);
            this.Questions.Remove(userCheck);
        }
    }
}
